#include "PluginManager.h"
#include <Windows.h>

namespace SEngine
{


    PluginManager::PluginManager(ConfigNode config)
        : m_config(config)
    {
    }

    std::shared_ptr<IPlugin> PluginManager::CreatePlugin(void* args)
    {
        try {
            auto dllPath = m_config.GetValue<ConfigNode::Object>()->get().at("Pipline").GetValue<ConfigNode::Object>()->get().at("path").GetValue<std::string>()->get();
            HMODULE hDll = LoadLibrary(TEXT(dllPath.c_str()));
            if (!hDll) return nullptr;
    
            auto funcCreate = (IPlugin* (*)(void*))GetProcAddress(hDll, "CreatePlugin");
            if (!funcCreate) return nullptr;
            
            IPlugin * plugin = funcCreate(args);
            plugin->Init();
            return std::shared_ptr<IPlugin>(plugin, [hDll](IPlugin* plugin) { 
                plugin->Deinit();
                auto funcDestroy = (void (*)(IPlugin*))GetProcAddress(hDll, "DestroyPlugin");
                if (!funcDestroy) return;
                funcDestroy(plugin);
                FreeLibrary(hDll);
            });
        } catch(...) {
            return nullptr;
        } 
    }


}
